package dyl.sys.service;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dyl.common.util.DylSqlUtil;
import dyl.common.util.JdbcTemplateUtil;
import dyl.sys.bean.MenuNav;
import dyl.sys.bean.SysAuthKind;
import dyl.sys.bean.SysMenu;
import dyl.sys.bean.SysUser;
import dyl.sys.bean.Ztree;
/**

 * @author Dyl
 * 2017-03-15 16:06:25
 */
@Service
public class SysMenuServiceImpl {
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	@Resource
	private SysAuthKindServiceImpl sysAuthKindServiceImpl;
	/**
	 * 获取左侧菜单
	 * @param sysUser
	 * @return
	 */
	public List<MenuNav> getMenu(SysUser sysUser){
		String sql = "";
		if(sysUser.isAdmin()){
			 if(!sysUser.getName().equals("dev")){
				 sql = "select * from sys_menu t where view_level>1 order by pid,oid";
			 }else{
				 sql = "select * from sys_menu t order by pid,oid";
			 }
		}else{
			String menuIds = "";
			for (BigDecimal menuId:sysUser.getMenuAuthMap().keySet()){
				menuIds+=menuId+",";
			}
			if(!menuIds.equals(""))menuIds = menuIds.substring(0,menuIds.length()-1);
			 if(DylSqlUtil.isORACLE){
				 sql = "select distinct * from sys_menu a start with a.id in ("+menuIds+") connect by prior a.pid = a.id";
			 }else if(DylSqlUtil.isMYSQL){
				 sql = "select group_concat(distinct pid) as pids from sys_menu a  where  a.id in ("+menuIds+")";
				 String pids = jdbcTemplate.queryForObject(sql,String.class);
				 sql = "select * from sys_menu a where a.id in ("+pids+","+menuIds+")";
			 }
		}
		List<MenuNav> menuNavList = jdbcTemplate.queryForListBean(sql,MenuNav.class);
		List<MenuNav> retNavList = new ArrayList<MenuNav>();
		//菜单只支持两级目录
		for (int i = 0; i < menuNavList.size(); i++){
			//第一级目录
			if(menuNavList.get(i).getPid()==null || menuNavList.get(i).getPid().intValue() == 0){
				retNavList.add(menuNavList.get(i));
			}else{
				//第二级目录
				for (int j = 0; j < retNavList.size(); j++){
					if(retNavList.get(j).getId().equals(menuNavList.get(i).getPid())){
						if(!sysUser.getName().equals("dev") && menuNavList.get(i).getId().intValue()==3 )continue;
						retNavList.get(j).addMenuNav(menuNavList.get(i));
					}
				}
			}
		}
			return retNavList;
	}
	/**
	 * 获取可分配的菜单
	 * @param sysUser
	 * @return
	 */
	public List<Ztree> getMenuForZtree(BigDecimal roleID){
		String sql ="select * from sys_menu t where view_level>1 order by pid,oid";
		List<SysMenu> mList = jdbcTemplate.queryForListBean(sql, SysMenu.class);
		List<Ztree> ztreeList = new ArrayList<Ztree>();
		for (SysMenu m:mList){
			Ztree ztree = new Ztree();
			ztree.setId(String.valueOf(m.getId()));
        	ztree.setpId(String.valueOf(m.getPid()));
        	ztree.setName(m.getTitle());
        	if(StringUtils.isNotEmpty(m.getUrl())){//如果有连接，则可以分配增删改查的权限
        		String kindSql = "select t.kind_id as id ,t2.name,t3.id as ck from sys_menu_kind t left join "
        				+ "(select * from sys_auth_role where role_id=?) t3 on t.kind_id=t3.kind_id and t3.menu_id=t.menu_id , "
        				+ "sys_kind t2 where t.kind_id = t2.id and t.menu_id = ?  order by t.kind_id ";
        	  List<SysAuthKind> kindList =  jdbcTemplate.queryForListBean(kindSql,new Object[]{roleID,ztree.getId()},SysAuthKind.class);
        	  for(SysAuthKind k:kindList){
        		  Ztree kindTree = new Ztree();
        		  kindTree.setId(m.getId()+"_"+k.getId());
        		  kindTree.setpId(String.valueOf(m.getId()));
        		  kindTree.setName(k.getName());
        		  if(k.getCk()!=null){//选中
        			  kindTree.setChecked(true);
        		  }
        		  ztreeList.add(kindTree);
        	  }
        	  /*if(kindList.size()==0){
        		  ztree.setNocheck(true);
        	  }*/
        	}
        	ztree.setNocheck(true);
        	ztreeList.add(ztree);
		}
		return ztreeList;
	}
	/**
	 * 菜单管理获取菜单
	 * @return
	 */
	public List<Ztree> getMenuForZtreeByManage(){
		String sql = "select * from sys_menu t order by pid ,oid";
		List<Ztree> ztreeList = jdbcTemplate.query(sql,new RowMapper<Ztree>(){
            @Override  
            public Ztree mapRow(ResultSet rs, int rowNum) throws SQLException{
            	Ztree ztree = new Ztree();
            	ztree.setId(rs.getString("id"));
            	ztree.setpId(rs.getString("pid"));
            	ztree.setName(rs.getString("title"));
                return ztree;
            }
        });
		//伪造一个根节点
		Ztree root = new Ztree();
		root.setName("根节点");
		root.setId(0+"");
		ztreeList.add(root);
		return ztreeList;
	}
	/**
	 * 说明：根据主键查询表sys_role中的一条记录 
	 * @return SysRole
	 */
	public SysMenu getSysMenu(BigDecimal  id) throws Exception{
		String sql = "select * from sys_menu where id=?";
		SysMenu sysMenu  = jdbcTemplate.queryForBean(sql, new Object[]{id},SysMenu.class); 
		if(StringUtils.isNotEmpty(sysMenu.getIcon())&&sysMenu.getIcon().indexOf("fa")==-1)sysMenu.setIcon(sysMenu.getIcon().substring(1,sysMenu.getIcon().length()));
		return sysMenu;
	}
	/**
	 * 说明：根据主键更新表sys_menu中的记录
	 * @return int >0代表操作成功
	 */
	@Transactional
	public int updateSysMenu(SysMenu sysMenu,String[] kind) throws Exception{
		String sql = "update sys_menu t set ";
		List<Object> con = new ArrayList<Object>();
			if(sysMenu.getTitle()!=null){
				sql+="t.title=?,";
				con.add(sysMenu.getTitle());
			}
			if(sysMenu.getNote()!=null){
				sql+="t.note=?,";
				con.add(sysMenu.getNote());
			}
			if(sysMenu.getState()!=null){
				sql+="t.state=?,";
				con.add(sysMenu.getState());
			}
			if(sysMenu.getUrl()!=null){
				sql+="t.url=?,";
				con.add(sysMenu.getUrl());
			}
			if(sysMenu.getActionClass()!=null){
				sql+="t.action_class=?,";
				con.add(sysMenu.getActionClass());
			}
			if(sysMenu.getIcon()!=null){
				sql+="t.icon=?,";
				if(sysMenu.getIcon().indexOf("fa")!=-1){
					con.add(sysMenu.getIcon());
				}else{
					if(sysMenu.getIcon().indexOf("&")==-1){
						con.add("&"+sysMenu.getIcon());
					}else{
						con.add(sysMenu.getIcon());
					}
				}
			}
		sql=sql.substring(0,sql.length()-1);
		sql+=" where id=?";
		con.add(sysMenu.getId());
		int returnVal=jdbcTemplate.update(sql,con.toArray());
		//更新菜单权限
		sysAuthKindServiceImpl.updateSysMenuKind(sysMenu.getId(), kind);
		//String[] kind
		return returnVal;
	}
	/**
	 * 新增菜单
	 * @param sysUser
	 * @return
	 */
	@Transactional
	public Ztree addMenu(Ztree ztree,SysUser sysUser){
		BigDecimal id = jdbcTemplate.queryForObject("select "+DylSqlUtil.getnextSeqNextVal()+" from dual", BigDecimal.class);
		//获取排序
		Integer oid = jdbcTemplate.queryForInt("select max(oid) from sys_menu where pid = ?",new Object[]{ztree.getpId()})+1;
		String sql = "insert into sys_menu(id,pid,oid,title,creator) values(?,?,?,?,?)";
		String title = "新节点"+id;
		jdbcTemplate.update(sql,new Object[]{id,ztree.getpId(),oid,title,sysUser.getCreator()});
		ztree.setName(title);
		ztree.setId(id.intValue()+"");
		return ztree;
	}
	/**
	 * 删除菜单以及菜单下的子菜单
	 * @param ztree
	 * @return
	 */
	@Transactional
	public int delete(BigDecimal id){
		//删除该节点下的所有子节点
		jdbcTemplate.update("delete from sys_menu where pid = ?",new Object[]{id});
		return jdbcTemplate.update("delete from sys_menu where id=?",new Object[]{id});
	}
	/**
	 * 移动节点
	 * @param moveType
	 * @param moveId
	 * @param targetId
	 * @return
	 */
	@Transactional
	public int move(String moveType,int moveId,int movePId,int targetId,int targetPId){
		int val = 0;
		int targetOid = 0;
		String type1 = "+";
		String type2 = ">";
		if(moveType.equals("inner")){//如果是变更为子节点，则为该节点最后
			targetOid = jdbcTemplate.queryForInt("(select max(oid) from sys_menu where pid = ?)",new Object[]{targetId});
			targetPId = targetId;
		}else{
			targetOid = jdbcTemplate.queryForInt("(select oid from sys_menu where id = ?)",new Object[]{targetId});
			if(moveType.equals("prev")){
				type1 = "-";
				type2 = "<";
			}
		}
		if(movePId != targetPId){//改变节点
			val = jdbcTemplate.update("update sys_menu set pid= ? where id = ?",new Object[]{targetPId,moveId});
		}
		val = jdbcTemplate.update("update sys_menu set oid=oid"+type1+"1 where pid = ? and oid "+type2+" ?",new Object[]{targetPId,targetOid});
		//修改移动节点的oid
		val = jdbcTemplate.update("update sys_menu set oid=?"+type1+"1 where id = ?",new Object[]{targetOid,moveId});
		return val;
	}
}
